import pygst
pygst.require('0.10')

import gst
import gobject
import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade

class Cam(gtk.Window):
	def __init__(self):
		gtk.Window.__init__(self)
		self.set_size_request(640, 480)
		self.connect('delete-event', self.delete_event_cb)
		vbox = gtk.VBox()
		self.add(vbox)
		self.viewer = CamViewer(self)
		vbox.pack_start(self.viewer, expand=True)
		
		hbox = gtk.HBox()
		vbox.pack_start(hbox, expand=False)

		button = gtk.Button('Play')
		button.connect('clicked', self.play_clicked_cb)		#self.viewer.play()
		hbox.pack_start(button, expand=False)

	def delete_event_cb(self, *args):
		self.viewer.stop()
		gtk.main_quit()

	def play_clicked_cb(self, *args):
		self.viewer.play()

class CamViewer(gtk.DrawingArea):
	def __init__(self, parent):
		self.parentw = parent
		gtk.DrawingArea.__init__(self)
		self.connect('destroy', self.destroy_cb)
		self.connect('expose-event', self.expose_cb)
		self.set_size_request(400, 400)

		#videoCaps = gst.Caps()
		#videoCaps.append("video/x-raw-yuv,width=(int)160")

		self.sink = gst.element_factory_make("xvimagesink")
		self.filter = gst.element_factory_make("ffmpegcolorspace")
		self.src = gst.element_factory_make('v4lsrc')
		# v4lsrc device=/dev/video0 autoprobe-fps=0 ! video/x-raw-yuv,width=640,height=480 ! xvimagesink
		self.src.set_property('autoprobe-fps', False)
		
		self.player = gst.Pipeline()
		self.player.add(self.src, self.filter, self.sink)
		gst.element_link_many(self.src, self.filter, self.sink)
		#self.filter.link_pads_filtered("src", self.sink, "sink", videoCaps)
		return
	
	def play(self):
		print "Play"
		self.sink.set_xwindow_id(self.window.xid)
		self.player.set_state(gst.STATE_PLAYING)
		
	def expose_cb(self, window, event):
        	self.sink.set_xwindow_id(self.window.xid)
		return
		
	def destroy_cb(self, da):
        	self.sink.set_xwindow_id(0L)
		return
	
	def stop(self):
		print "Stop"
		self.player.set_state(gst.STATE_NULL)
		return
		
if __name__ == "__main__":
	w = Cam()
	w.show_all()
	gtk.main()
